package com.imcrl.component.pictab
{
	import com.imcrl.component.ext.ButtonImage;
	import com.imcrl.component.ext.Sprite;
	import com.imcrl.component.page.Page;
	import com.imcrl.core.ClassFactory;
	import com.imcrl.core.IResizeable;
	import com.imcrl.core.imcrl_internal;
	import com.imcrl.core.state.StateMachine;
	import com.imcrl.event.ListItemEvent;
	import com.imcrl.manager.Pool;
	
	import flash.display.BitmapData;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	import starling.animation.Tween;
	import starling.core.Starling;
	import starling.display.DisplayObjectContainer;
	import starling.display.Image;
	import starling.events.Event;
	import starling.events.Touch;
	import starling.events.TouchEvent;
	import starling.events.TouchPhase;
	import starling.textures.Texture;
	
	import starlingui.manager.TextureLoader;
	import starlingui.manager.TextureResource;

	use namespace imcrl_internal;
	public class PictabQ extends Sprite implements IResizeable
	{

		public static const AUTO_VIEW_NUMBER:int=5;
		
		protected var len:int=0;
		
		private var position:int=0;
		
		private var factory:ClassFactory;

		protected var items:Vector.<PictabItem>;
		
		imcrl_internal var _background:Image;
		
		/**
		 * 只移动这个容器的座标; 
		 */		
		imcrl_internal var container:DisplayObjectContainer;
		
		/**
		 * 当前所在索引
		 */		
		protected var currentIndex:int;
		
		
		/**
		 * 必须提供length; 
		 */		
		protected var _data:*;
		
		private var stateMachine:StateMachine;
		public function PictabQ(factory:ClassFactory)
		{
			
			this.factory=factory;
			items=new Vector.<PictabItem>();
			
			container=new Sprite();
			var item:PictabItem;
			var i:int=0;
			while(i<AUTO_VIEW_NUMBER){
				item=factory.newInstance();
				item.index=i++;
				items.push(item);
				container.addChild(item);
			}
			
			
			this.addChild(container);
			
			scrollEnabeld=true;
		}
		
		public function set scrollEnabeld(bool:Boolean):void{
			if(bool==false){
				removeEventListener(TouchEvent.TOUCH,touchHandler);
			}else{
				addEventListener(TouchEvent.TOUCH,touchHandler);
			}
		}
		
		public function set backgournd(url:String):void{
			var textLoader:TextureLoader=TextureResource.getURL(url);
			if(textLoader.isReady){
				initBbackgroundTexture(textLoader.texture);
				return;
			}
			textLoader.addEventListener(Event.COMPLETE,backgroundHandle);
		}
		
		protected function backgroundHandle(event:Event):void{
			var textLoader:TextureLoader =event.target as TextureLoader;
			textLoader.addEventListener(Event.COMPLETE,backgroundHandle);
			initBbackgroundTexture(textLoader.texture);
		}
		
		/**
		 * 设置背景贴图 
		 * @param textLoader
		 * 
		 */		
		protected function initBbackgroundTexture(value:Texture):void{
			if(_background==null){
				_background=new ButtonImage(value);
				this.addChildAt(_background,0);
			}else{
				_background.texture=value;
				_background.readjustSize();
			}
		}
		
		private var mx0:int;
		private var my0:int;
		
		private var mx:int;
		private var my:int;
		
		private var isMouseDown:Boolean=false;
		protected function touchHandler(event:TouchEvent):void{
			var touch:Touch=event.getTouch(this);
			if(touch==null)return;
			
			var mouseCaption:Point=touch.getLocation(this);

			switch(touch.phase){
				case TouchPhase.BEGAN :
					
					mx=mx0=mouseCaption.x;
					my=my0=mouseCaption.x;
					
					isMouseDown=true;
					break;
				
				case TouchPhase.ENDED :
					isMouseDown=false;
					
					var dx:int=mouseCaption.x-mx0;
					var dy:int=mouseCaption.x-my0;
					
					if(dx==0 && dy==0){
						break;
					}
					
					var len:int=Math.sqrt(dx*dx+dy*dy);
					
					if(len>halfSceneW){
						var bool:Boolean;
						if(dx<0 || dy<0){
							bool=next(current);
						}else{
							bool=prev(current);
						}
						
						if(bool && hasEventListener(ListItemEvent.CHANGE)){
							this.dispatchEvent(new ListItemEvent(ListItemEvent.CHANGE));
						}
					}else{	
						back(current);
					}
					
					break;
				
				
				case TouchPhase.MOVED :
					if(isMouseDown==false)return;
					container.x+=mouseCaption.x-mx;
					mx=mouseCaption.x; 
					break;
			}
		}
		
		
		
		public function getItem(index:int):PictabItem{
			var item:PictabItem=items[index];
			if(item==null){
				item=factory.newInstance();
				items[index]=item;
			}
			return item;
		}
		
		
		
		override public function set scrollRect(value:Rectangle):void
		{
			super.scrollRect=value;
			
			this.resize(value.width,value.height);
		}
		
		
		protected var sceneWidth:int;
		protected var sceneHeight:int;
		imcrl_internal var halfSceneW:int;
		public function resize(w:int,h:int):void{
			this.sceneWidth=w;
			this.sceneHeight=h;
			this.halfSceneW=w>>2;
			for each(var item:PictabItem in items){
				item.resize(w,h);
				item.x=item.index*w;
			}
		}
		
		
		
		public function displayList(value:*):void{
			
			this._data=value;
			this.len=value.length;
			
			var i:int=0;
			
			var item:PictabItem;
			var itemData:*;
			
			
			var min:int=Math.min(len,AUTO_VIEW_NUMBER);
			while(i<min){
				
				item=getItem(i);
				
				item.index=i;
				item.data=getItemData(i);
			
				item.x=i*sceneWidth;
				
				if(i<2){
					item.awaken();
				}
				
				i++;
			}
			
			currentIndex=0;
		}
		
		public function get data():Page{
			return _data;
		}
		
		imcrl_internal function next(target:PictabItem):Boolean{
			var index:int=target.index;
			
			if(index==len-1){
				back(target);
				return false;
			}
			
			currentIndex=index+1;
			check(currentIndex,true);
			
			containerX=-(currentIndex)*sceneWidth;
			return true;
		}
		
		imcrl_internal function prev(target:PictabItem):Boolean{
			var index:int=target.index;
			if(index==0){
				back(target);
				return false;
			}
			
			
			currentIndex=index-1;
			check(currentIndex,false);
			
			containerX=-(currentIndex)*sceneWidth;
			return true;
		}
		
		
		imcrl_internal function back(target:PictabItem):void{
			trace("back");
			currentIndex=target.index;
			containerX=-currentIndex*sceneWidth;
		}
		
		
		public function get containerX():Number{
			return container.x;
		}
		
		private var moveTween:Tween=new Tween(null,1);
		public function set containerX(value:Number):void{
			moveTween.reset(container,0.2);
			
			moveTween.animate("x",value);
			moveTween.onComplete=onComplete;
			moveTween.onCompleteArgs=[value];
			
			this.touchable=false;
			
			Starling.current.juggler.add(moveTween);
		}
		private function onComplete(x:int):void{
			container.x=x;
			this.touchable=true;
		}
		
		private function check(index:int,add:Boolean):void{
			//trace("check",index,len,add)

			var pictabIndex:int=-1;
			
			if(add){
				if(index<3 || index>len-3){
					progressPictabIndex(index,add);
					return;
				}
			}else{
				if(index<2 || index>=len-3){
					progressPictabIndex(index,add);
					return;
				}
			}
			
			//("do",index,len,add)
			var item:PictabItem;
			if(add){
				item=items.shift();
				item.index=index+2;
				item.x=item.index*sceneWidth;
				
				items.push(item);
				
				
				items[0].sleep();
				items[3].awaken();
				
			}else{
				item=items.pop();
				item.index=index-2;
				item.x=item.index*sceneWidth;
				
				items.unshift(item);
				
				
				items[1].awaken();
				items[4].sleep();
			}
			
			
			item.sleep();
			item.data=getItemData(item.index);
			
		}
		
		public function getItemData(index:int):*{
			return _data[index];
		}
		
		
		/**
		 * 设置索引 
		 * @param value
		 * @param add
		 * 
		 */		
		public function progressPictabIndex(value:int,add:Boolean):void{
			var index:int=-1;
			for(var i:int=0;i<AUTO_VIEW_NUMBER;i++){
				if(items[i].index==value){
					index=i;
					break;
				}
			}
			
			if(index==-1)return;
			
			
			
			if(index+1<=AUTO_VIEW_NUMBER-1){
				items[index+1].awaken();
			}
			if(index-1>=0){
				items[index-1].awaken();
			}
			

			if(add){
				
				if(index-2>=0){
					items[index-2].sleep();
				}
				
			}else{
				if(index+2<=AUTO_VIEW_NUMBER-1){
					items[index+2].sleep();
				}
			}
		}
		
		
		public function get current():PictabItem{
			for each(var item:PictabItem in items){
				if(item.index==currentIndex)return item;
			}
			return null;
		}
		
	}
}